<template>
  <el-row :gutter="20">
    <el-col :span="12">
      <button @click="handleClick">更新列表</button>
      <el-table
        v-if="reRender"
        ref="table1"
        :data="list"
        row-key="id">
        <el-table-column prop="id" label="序号" width="80px"></el-table-column>
        <el-table-column prop="label" label="标题"></el-table-column>
      </el-table>
    </el-col>
    <el-col :span="12">
      <el-table
        ref="table2"
        :data="list2"
        row-key="id">
        <el-table-column prop="id" label="序号" width="80px"></el-table-column>
        <el-table-column prop="label" label="标题"></el-table-column>
      </el-table>
    </el-col>
  </el-row>
</template>

<script>
import Sortable from 'sortablejs'
export default {
  data() {
    return {
      reRender: true,
      list: [
        { id: 1, label: 'title1' },
        { id: 2, label: 'title2' },
        { id: 3, label: 'title3' }
      ],
      list2: [
        { id: 1, label: 'title1' },
        { id: 2, label: 'title2' },
        { id: 3, label: 'title3' }
      ],
      list3: [
        { id: 1, label: 'test1' },
        { id: 2, label: 'test2' },
        { id: 3, label: 'test3' }
      ]
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.newSet()
      this.newSet2()
    })
  },
  methods: {
    newSet() {
      const el = this.$refs.table1.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      const that = this
      this.sortable = Sortable.create(el, {
        group: {
          name: 'table',
          pull: 'clone'
        },
        animation: 150,
        onEnd: (evt) => {
          var oldIndex = evt.oldIndex
          var $li = evt.item
          var $oldli = evt.clone
          console.log(oldIndex, $li, $oldli)

          const nextSlibing = $oldli.nextSibling

          el.removeChild($oldli) // 先删除守旧的节点
          el.insertBefore(evt.item, nextSlibing) // 还原节点

          // 更新items数组
          var item = that.list.splice(oldIndex, 1)
          that.list.splice(oldIndex, 0, item[0])
        }
      })
    },

    newSet2() {
      const el = this.$refs.table2.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        group: {
          name: 'table',
          pull: 'clone'
        },
        animation: 150,
        onAdd: evt => {
          console.log(evt, 'add')
        }
      })
    },
    handleClick() {
      this.list = this.list3
    }
  }
}
</script>

<style>
</style>
